import { Component, OnInit, ViewChild, OnDestroy, inject } from '@angular/core';
import { PageHeaderModule } from '@delon/abc/page-header';
import { STPage, STComponent, STColumn, STChange, STModule } from '@delon/abc/st';
import { DelonACLModule } from '@delon/acl';
import { DelonFormModule, SFSchema } from '@delon/form';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Api } from 'src/app/shared/api/api';
import { BaseAbilityComponent } from 'src/app/shared/base.ability.component';
import { DELETED_STATUS_BADGE, DELETED_STATUS_ENUM } from 'src/app/shared/constant/common-constant';
import { ResponseCode } from 'src/app/shared/response.code';

import { ApplicationEditComponent } from './application-edit.component';

@Component({
  selector: 'app-system-application',
  templateUrl: './application.component.html',
  imports: [PageHeaderModule, NzCardModule, NzButtonModule, STModule, DelonACLModule, DelonFormModule]
})
export class ApplicationComponent extends BaseAbilityComponent implements OnInit, OnDestroy {
  params: NzSafeAny = {};
  searchParams: NzSafeAny = { deleted: false };
  page: NzSafeAny = {
    records: [],
    current: 1,
    total: 0,
    size: 10
  };
  pagination: STPage = {
    front: false,
    pageSizes: [10, 20, 30, 40, 50],
    total: true,
    showSize: true,
    showQuickJumper: true
  };
  searchSchema: SFSchema = {
    properties: {
      code: {
        type: 'string',
        title: '编码',
        ui: {
          acl: { ability: ['query'] }
        }
      },
      name: {
        type: 'string',
        title: '名称',
        ui: {
          acl: { ability: ['query'] }
        }
      },
      deleted: {
        type: 'string',
        title: '状态',
        default: false,
        enum: DELETED_STATUS_ENUM,
        ui: {
          widget: 'select',
          acl: { ability: ['query'] }
        }
      }
    }
  };
  @ViewChild('st', { static: true }) st!: STComponent;
  columns: STColumn[] = [
    { title: '编码', index: 'code' },
    { title: '名称', index: 'name' },
    { title: '描述', index: 'description' },
    { title: '状态', index: 'deleted', type: 'badge', badge: DELETED_STATUS_BADGE },
    {
      title: '操作',
      buttons: [
        {
          text: '编辑',
          icon: 'edit',
          type: 'modal',
          modal: {
            component: ApplicationEditComponent,
            drag: true
          },
          click: () => {
            this.query();
          },
          acl: { ability: ['edit'] }
        },
        {
          text: '删除',
          icon: 'delete',
          iif: record => record.type !== 5 && !record.deleted,
          click: (record: NzSafeAny) => {
            this.delete(record);
          },
          acl: { ability: ['delete'] }
        }
      ]
    }
  ];

  protected readonly http = inject(_HttpClient);
  private readonly msg = inject(NzMessageService);
  protected readonly modal = inject(ModalHelper);
  private readonly modalService = inject(NzModalService);

  ngOnInit() {
    super.initAbilities();
    this.query();
  }

  ngOnDestroy(): void {
    super.clearAbilities();
  }

  change(e: STChange) {
    if (e.type === 'pi' || e.type === 'ps') {
      this.params.size = e.ps;
      this.params.current = e.pi;
      this.query();
    }
  }

  search(event: NzSafeAny) {
    if (event) {
      if (event.code) {
        this.searchParams.code = event.code;
      } else {
        delete this.searchParams.code;
      }
      if (event.name) {
        this.searchParams.name = event.name;
      } else {
        delete this.searchParams.name;
      }
      if (event.deleted !== null) {
        this.searchParams.deleted = event.deleted;
      } else {
        delete this.searchParams.deleted;
      }
      this.query();
    }
  }

  query() {
    const current: number = this.params.current || 1;
    const size: number = this.params.size || 10;
    this.http.get(`${Api.BaseSysApplicationApi}/page/${current}/${size}`, this.searchParams).subscribe((res: NzSafeAny) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data) this.page = res.data;
      }
    });
  }

  add() {
    this.modal.createStatic(ApplicationEditComponent, {}, { drag: true }).subscribe(() => this.st.reload());
  }

  delete(record: NzSafeAny) {
    console.log(record);
    this.modalService.confirm({
      nzTitle: '确定删除吗?',
      nzContent: '<b style="color: red;">如果您确定要删除请点击确定按钮，否则点取消</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () =>
        this.http.delete(`${Api.BaseSysApplicationApi}/${record.id}`).subscribe((res: NzSafeAny) => {
          if (res) {
            if (res.code === ResponseCode.SUCCESS) {
              this.st.reload();
              this.msg.success('删除成功');
            } else {
              this.msg.warning(res.message);
            }
          } else {
            this.msg.error('删除失败，未知错误');
          }
        }),
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
}
